// api/request.js
const baseUrl = '/api'; // 基础 API 地址

function request(options) {
	return new Promise((resolve, reject) => {
		const config = {
			url: baseUrl + options.url,
			method: options.method || 'GET',
			data: options.data || {},
			header: options.header || {
				'Content-Type': 'application/json'
			},
			success: (res) => {
				if (res.statusCode === 200) {
					if (res.data.code === 1) {
						resolve(res.data.data);
					} else if (res.data.code === -9){
						const token = uni.getStorageSync('token');
						if (!token){
							uni.showModal({
								title: '登录确认',
								content: '请您先进行登录！',
								showCancel: false,
								success: function(res) {
									if (res.confirm) {
										uni.navigateTo({
											url: '/pages/login/index'
										});
									}
								}
							});
						} else {
							uni.showModal({
								title: '登录失效',
								content: res.data.msg,
								showCancel: false,
								success: function(res) {
									if (res.confirm) {
										uni.redirectTo({
										    url: '/pages/login/index'
										});
									}
								}
							});
						}
						reject(res.data);
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: 'fail',
							duration: 1000
						});
						reject(res.data);
					}
				} else {
					reject(new Error(`请求失败，状态码：${res.statusCode}`));
				}
			},
			fail: (err) => {
				reject(err);
			}
		}
		const token = uni.getStorageSync('token');
		if (token){
			config.header['jwtToken'] = token;
		}
		uni.request(config);
	});
}

export default request;